package com.start.admin.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.start.admin.entity.StartSysUser;
import com.start.admin.entity.StartSysUserManageDept;
import com.start.admin.entity.StartSysUserRole;
import com.start.admin.service.StartSysRoleService;
import com.start.admin.service.StartSysUserManageDeptService;
import com.start.admin.service.StartSysUserRoleService;
import com.start.admin.service.StartSysUserService;
import com.start.admin.vo.StartSysUserVo;
import com.start.common.api.Result;
import com.start.common.dataImport.DataImportEntity;
import com.start.common.dataImport.ImportExportUtils;
import com.start.common.dataRule.DataQueryConstructor;
import com.start.common.details.BaseUserDetails;
import com.start.common.entity.StartBaseEntity;
import com.start.common.entity.StartBaseUser;
import com.start.core.annotations.RegisterMenu;
import com.start.core.annotations.RegisterPermission;
import com.start.core.annotations.StartLog;
import com.start.core.vo.BaseUpdatePassword;
import com.start.security.StartTokenTools;
import com.start.security.annotations.DataPermission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/start/sysUser")
@RegisterMenu(value = "用户管理", parentId = "9bd73d5ccbf34c4c0fc4c038eb31ca2e", systemCode = "sys:user", component = "views/sys/user/index", path = "/user")
public class StartSysUserController {
    @Autowired
    private StartSysUserService sysUserService;

    @GetMapping("/page")
    @DataPermission("views/sys/user/index")
    public Result<?> page(Page<StartSysUser> page, StartSysUser entity) {
        QueryWrapper<StartSysUser> sysUserQueryWrapper = DataQueryConstructor.createEntity(StartSysUser.class);
        LambdaQueryWrapper<StartSysUser> lambdaQuery = sysUserQueryWrapper.lambda();
        Page<StartSysUser> result = sysUserService.page(page, lambdaQuery);
        return Result.ok(result);
    }

    @PostMapping("/add")
    @StartLog(value = "系统用户管理", action = "添加用户")
    @PreAuthorize("@pas.hasPermission('sys:user:add')")
    @RegisterPermission(value = "sys:user:add", name = "新增")
    public Result add(@RequestBody StartSysUser entity) {
        sysUserService.createUser(entity);
        return Result.ok();
    }

    @StartLog(value = "系统用户管理", action = "修改用户信息")
    @PutMapping("/updateById")
    @PreAuthorize("@pas.hasPermission('sys:user:edit')")
    @RegisterPermission(value = "sys:user:edit", name = "编辑")
    public Result updateById(@RequestBody StartSysUser entity) {
        sysUserService.updateById(entity);
        return Result.ok();
    }

    @Autowired
    private StartSysRoleService startSysRoleService;

    @Autowired
    private StartSysUserManageDeptService userDeptService;

    @Autowired
    private StartSysUserRoleService startSysUserRoleService;

    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable("id") String id) {
        StartSysUser startSysUser = sysUserService.getById(id);
        List<StartSysUserRole> roleList = startSysUserRoleService.listByUserId(startSysUser.getId());
        List<StartSysUserManageDept> startSysUserManageDepts = userDeptService.listByUserId(startSysUser.getId());
        StartSysUserVo userVo = StartSysUserVo.getInstance(startSysUser, roleList, startSysUserManageDepts);
        return Result.ok(userVo);
    }

    @GetMapping("/getUserInfo/{id}")
    public Result<?> getUserInfo(@PathVariable("id") String id) {
        if (StringUtils.isEmpty(id)) {
            BaseUserDetails currentUser = StartTokenTools.getCurrentUser();
            id = currentUser.getUserId();
        }
        StartBaseUser sysUser = sysUserService.getById(id);
        if (sysUser != null) {
            sysUser.setUserPwd(null);
        }
        return Result.ok(sysUser);
    }

    @GetMapping("/getUserByIds")
    public Result<?> getUserByIds(String ids) {
        if (ids.length() < 1) {
            return Result.ok();
        }
        List<String> id = Arrays.asList(ids).stream().filter(StringUtils::isAllBlank).collect(Collectors.toList());
        LambdaQueryWrapper<StartSysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(StartBaseEntity::getId, id);
        lambdaQueryWrapper.select(StartBaseEntity::getId, StartBaseUser::getRealName, StartBaseUser::getNickName, StartBaseUser::getUserName, StartBaseUser::getUserType);
        return Result.ok(sysUserService.list(lambdaQueryWrapper));

    }

    @StartLog(value = "系统用户管理", action = "删除用户信息")
    @DeleteMapping("/deleteById/{id}")
    @PreAuthorize("@pas.hasPermission('sys:user:delete')")
    @RegisterPermission(value = "sys:user:delete", name = "删除")
    public Result<?> deleteById(@PathVariable("id") String id) {
        sysUserService.removeById(id);
        return Result.ok();
    }


    @GetMapping("/downloadTemplate")
    @PreAuthorize("@pas.hasPermission('sys:user:downloadTemplate')")
    @RegisterPermission(value = "sys:user:downloadTemplate", name = "下载导入模板")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "系统用户导入模板.xls";
        try {
            ImportExportUtils.createImportTemplate(StartSysUser.class, response, fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/exportExcel")
    @PreAuthorize("@pas.hasPermission('sys:user:exportExcel')")
    @RegisterPermission(value = "sys:user:exportExcel", name = "导出excel")
    @DataPermission("views/sys/user/index")
    public void exportExcel(HttpServletResponse response) {
        String fileName = "系统用户导出.xls";
        QueryWrapper<StartSysUser> queryWrapper = DataQueryConstructor.createEntity(StartSysUser.class);
        List<StartSysUser> list = sysUserService.list(queryWrapper);
        ImportExportUtils.exportExcel(StartSysUser.class, list, response, fileName);
    }


    @PostMapping("/importExcel")
    @PreAuthorize("@pas.hasPermission('sys:user:importExcel')")
    @RegisterPermission(value = "sys:user:importExcel", name = "导入excel")
    public Result<?> importExcel(@RequestBody DataImportEntity entity) {
        List<String> filePaths = entity.getFilePath();
        if (filePaths == null || filePaths.size() < 1) return Result.ok();
        List<StartSysUser> dateList = ImportExportUtils.importExcelFile(StartSysUser.class, filePaths.get(0));
        if (dateList.size() < 1) {
            return Result.ok();
        }
        for (StartSysUser user : dateList) {
            user.setUserPwd("0000");
        }
        log.info("文件导入:" + JSON.toJSONString(dateList));
        sysUserService.saveBatch(dateList, 30);
        return Result.ok();
    }


    @StartLog(value = "系统用户管理", action = "修改其他用户密码")
    @PutMapping("/updateUserPassword")
    @PreAuthorize("@pas.hasPermission('sys:user:updateUserPassword')")
    @RegisterPermission(value = "sys:user:updateUserPassword", name = "密码修改")
    public Result updateUserPassword(@RequestBody BaseUpdatePassword model) {
        sysUserService.updateUserPassword(model);
        return Result.ok();
    }


    @StartLog(value = "系统用户管理", action = "修改锁定状态")
    @GetMapping("/updateUserLockedState/{userId}")
    @PreAuthorize("@pas.hasPermission('sys:user:updateUserLockedState')")
    @RegisterPermission(value = "sys:user:updateUserLockedState", name = "修改锁定状态")
    public Result updateUserLockedState(@PathVariable("userId") String userId, Integer state) {
        sysUserService.updateUserLockedState(userId, state);
        return Result.ok();
    }

    @StartLog(value = "系统用户管理", action = "修改启用状态")
    @GetMapping("/updateUserEnabledState/{userId}")
    @PreAuthorize("@pas.hasPermission('sys:user:updateUserEnabledState')")
    @RegisterPermission(value = "sys:user:updateUserEnabledState", name = "修改启用状态")
    public Result updateUserEnabledState(@PathVariable("userId") String userId, Integer state) {
        sysUserService.updateUserEnabledState(userId, state);
        return Result.ok();
    }
}
